package com.nineclock.auth.processor.impl;

import com.nineclock.auth.entity.IntegrationAuthenticationEntity;
import com.nineclock.auth.processor.AuthenticationProcessor;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.feign.SysUserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Component
public class SmsAuthenticationProcessor implements AuthenticationProcessor {

    @Autowired
    RedisTemplate<String, String> redisTemplate;


    @Autowired
    SysUserFeign userFeign;

    @Override
    public SysUserDTO authenticate(IntegrationAuthenticationEntity entity) {
        String mobile = entity.getAuthParameter("mobile");
        String password = entity.getAuthParameter("password");
        if(mobile == null || password == null){
            throw new NcException(ResponseEnum.INVALID_USERNAME_PASSWORD);
        }

        //调用系统微服务获取 用户对象(账号：手机号 ， 密码： 数据库的密码)
        SysUserDTO userDto = userFeign.queryUser(mobile).getData();
        if(userDto == null){
            throw new NcException(ResponseEnum.USER_NOT_REGISTER);
        }


        //从redis中获取 验证码
        String key = SMSConstant.SMS_LOGIN_KEY_PREFIX + mobile;
        String redisCode = redisTemplate.boundValueOps(key).get();

        if(redisCode == null){
            throw new NcException(ResponseEnum.CODE_IMAGE_ERROR);
        }
        //把验证码转换为密文返回
        userDto.setPassword(new BCryptPasswordEncoder().encode(redisCode));

        return userDto;
    }

    @Override
    public boolean support(IntegrationAuthenticationEntity entity) {
        if(entity != null && "sms".equals(entity.getAuthType())){
            return true;
        }
        return false;
    }
}
